package com.lancoo.answer.helper.answer;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import com.lancoo.answer.R;
import com.lancoo.answer.model.AnswerConstant;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.bean.Child;
import com.lancoo.answer.model.bean.ExamViewBean;
import com.lancoo.answer.model.bean.Item;
import com.lancoo.answer.model.bean.Ques;
import com.lancoo.answer.model.bean.Type;
import com.lancoo.answer.model.entity.TaskControlBean;
import com.lancoo.answer.model.eventBean.FillAnswerEventBean;
import com.lancoo.answer.util.EditTextInputUtil;
import com.lancoo.answer.util.ExamFontSizeAdjustUtils;
import com.lancoo.answer.util.NetWorkTools;
import com.lancoo.answer.util.SoftInputUtils;
import com.lancoo.answer.util.paperUtils.FragmentCommunicationUtils;
import com.lancoo.answer.widget.WaveView;
import com.rxjava.rxlife.RxLife;
import com.stkouyu.LancooSpeechRecognitionManager;
import com.stkouyu.listener.OnLancooSpeechRecognitionListener;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by pengmi on 2021/12/20 14:38
 * Description:
 */
public class FillAnswerFragment extends Fragment implements View.OnTouchListener{

    private static final String TAG = "FillAnswerFragment";
    private EditText editText;
    private Item item;
    private long subTime;
    private WaveView waveView;
    private PopupWindow popupWindow;
    private View convertView;
    private int typeIndex;
    private int quesIndex;
    private int childIndex;
    private int itemIndex;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        convertView = inflater.inflate(R.layout.ev_layout_pop_fill_answer,container,false);
        return convertView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.e(TAG, "onViewCreated: " );
        adjustFontSize();
        if(getArguments()==null){
            return;
        }
        editText = view.findViewById(R.id.edittext);
        EditTextInputUtil.disableCopyAndPaste(editText);

        TextView tv_index = view.findViewById(R.id.tv_order_index);
        typeIndex = getArguments().getInt(AnswerConstant.KEY_TYPEINDEX);
        quesIndex = getArguments().getInt(AnswerConstant.KEY_QUESINDEX);
        childIndex = getArguments().getInt(AnswerConstant.KEY_CHILDINDEX);
        itemIndex = getArguments().getInt(AnswerConstant.KEY_ITEMINDEX);
        ExamViewBean constantExamBean = ConstantBean.Companion.getConstantExamBean();
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        if(constantExamBean==null){
            return;
        }
        if(taskControlBean==null){
            return;
        }
        if(constantExamBean.getTypeList()==null){
            return;
        }
        Type type = constantExamBean.getTypeList().get(typeIndex);
        if(type.getQuesList()==null){
            return;
        }
        Ques ques = type.getQuesList().get(quesIndex);
        if(TextUtils.equals(ques.getTypeNo(),"S")||taskControlBean.isCloseMediaAnswer()){//听力填空，屏蔽音频作答功能
            view.findViewById(R.id.img_microphone).setVisibility(View.GONE);
        }
        if(ques.getChildList()==null){
            return;
        }
        Child child=ques.getChildList().get(childIndex);
        if(TextUtils.equals("0", child.getSortIndexType())){
            if(child.getItemList()!=null&&child.getItemList().size()>1){//一题多空
                tv_index.setText(String.format("%s.",  child.getItemList().get(0).getSortIndex()+"-"+(itemIndex +1)));
            }else{
                tv_index.setText(String.format("%s.", child.getItemList().get(0).getSortIndex()));
            }
        }else {
            List<Item> itemList = child.getItemList();
            if(itemList==null){
                return;
            }
            tv_index.setText(String.format("%s.",child.getItemList().get(itemIndex).getSortIndex() ));
        }
        if(child.getItemList()==null){
            return;
        }
        item=child.getItemList().get(itemIndex);
        if(item.getStuAnswer()!=null&&!TextUtils.isEmpty(item.getStuAnswer())){
            editText.setText(item.getStuAnswer());
            editText.setSelection(item.getStuAnswer().length());
        }
        SoftInputUtils.setEditTextInputSpace(editText);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String lastAnswer=item.getStuAnswer();
                item.setStuAnswer(editable.toString().trim());
                if(!TextUtils.equals(lastAnswer,editable.toString().trim())){
                    if(getParentFragment() instanceof FillAnswerDialog){
                        FillAnswerEventBean bean=new FillAnswerEventBean();
                        bean.setTypeIndex(typeIndex);
                        bean.setQuesIndex(quesIndex);
                        bean.setChildIndex(childIndex);
                        bean.setItemIndex(itemIndex);
                        bean.setLastChidIndex(childIndex);
                        bean.setLastQuesIndex(quesIndex);
                        bean.setMsgType(0);
                        EventBus.getDefault().post(bean);
                    }
                }
            }
        });
        view.findViewById(R.id.img_microphone).setOnTouchListener(this);


    }

    public static Fragment loadFragment(int typeIndex,int quesIndex,int childIndex,int itemIndex){
        FillAnswerFragment fragment=new FillAnswerFragment();
        Bundle bundle=new Bundle();
        bundle.putInt(AnswerConstant.KEY_TYPEINDEX,typeIndex);
        bundle.putInt(AnswerConstant.KEY_QUESINDEX,quesIndex);
        bundle.putInt(AnswerConstant.KEY_CHILDINDEX,childIndex);
        bundle.putInt(AnswerConstant.KEY_ITEMINDEX,itemIndex);
        fragment.setArguments(bundle);
        return fragment;
    }


    public void getEditTextFocus(){
        if(editText!=null){
            editText.setFocusable(true);
            editText.requestFocus();
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                subTime= System.currentTimeMillis();
                startRecognition();
                v.getParent().requestDisallowInterceptTouchEvent(true);
                FragmentCommunicationUtils.testEventBus();
                return true;
            case MotionEvent.ACTION_UP:
                if(NetWorkTools.isNetworkConnected(getContext())){
                    boolean isResult= System.currentTimeMillis()-subTime>=200;
                    stopRecognition(isResult);
                }else{
                    stopRecognition(false);
                    Toast.makeText(getContext(),"抱歉，当前网络不可用", Toast.LENGTH_SHORT).show();
                }
                return true;
            case MotionEvent.ACTION_CANCEL:
//                stopRecognition(false);
                return true;
        }
        return false;
    }


    private void startRecognition(){
        if(getActivity()==null||getContext()==null){
            return;
        }
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED) {
//            Toast.makeText(getApplicationContext(), "没有获取权限,请手动开启权限", Toast.LENGTH_SHORT).show();
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            String[] pressisionArray;
            try {
                pressisionArray = new String[]{Manifest.permission.RECORD_AUDIO};
                ActivityCompat.requestPermissions( getActivity(), pressisionArray, 100);//,Manifest.permission.READ_PHONE_STATE
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }
        showRecordPop();
        LancooSpeechRecognitionManager.getInstance(getContext())
                .startSpeechRecognition(0, new OnLancooSpeechRecognitionListener() {
                    @Override
                    public void onSpeechRecognitionStart() {

                    }

                    @Override
                    public void onSpeechRecogniting(int vad_status, int sound_intensity) {
                        Observable.create((ObservableOnSubscribe<Integer>) emitter -> {
                                    emitter.onNext(sound_intensity);
                                })
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .as(RxLife.as(FillAnswerFragment.this))
                                .subscribe(o -> {
                                    if (waveView != null) {
                                        waveView.setVisibility(View.VISIBLE);
                                        waveView.addData((short) sound_intensity);
                                    }
                                }, throwable -> {

                                });
                    }

                    @Override
                    public void onSpeechRecognitionEnd(String recognitionSentence, String url) {
                        appendAnswer(recognitionSentence);
                    }

                    @Override
                    public void onSpeechRecognitionError(String error) {

                    }
                });
    }

    private void stopRecognition(boolean isEnd){
        LancooSpeechRecognitionManager.getInstance(getContext()).stopSpeechRecognition(isEnd);
        if(popupWindow!=null&&popupWindow.isShowing()){
            popupWindow.dismiss();
        }
    }

    private void appendAnswer(String appendContent){
        editText.setText(appendContent);
        editText.setSelection(editText.getText().toString().length());
    }

    private void showRecordPop(){
        @SuppressLint("InflateParams") View inflater= LayoutInflater.from(getContext()).inflate(R.layout.ev_layout_pop_recording,null);
        popupWindow = new PopupWindow(inflater,
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(false);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        popupWindow.showAtLocation(convertView, Gravity.CENTER,0,0);
        waveView = inflater.findViewById(R.id.waveview);
    }

    /**
     * 关闭音频作答
     */
    public void closeAudioAnswer(){
        if(convertView==null){
            return;
        }
        convertView.findViewById(R.id.img_microphone).setEnabled(false);
        Log.e("eee","填空题已关闭");
        if(popupWindow!=null&&popupWindow.isShowing()){
            LancooSpeechRecognitionManager.getInstance(getContext()).stopSpeechRecognition(true);
            popupWindow.dismiss();
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        if(editText!=null){
            if(getContext()==null){
                return;
            }
            Log.e("填空作答","onResume"+quesIndex+","+childIndex+","+itemIndex);
        }
    }

    private void adjustFontSize(){
        TextView textView = convertView.findViewById(R.id.tv_order_index);
        TextView edittext = convertView.findViewById(R.id.edittext);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView,13);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(edittext,13);
    }
}
